<template>
  <div>
    <common-head title="联系人列表"/>
    <div class="wrap">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="selectContact"
      />
    </div>
  </div>
</template>

<script>
import CommonHead from '../../components/CommonHead.vue'
import { fetchContact } from 'api'
import { getToken } from '../../utils/index'
export default {
  data () {
    return {
      chosenAddressId: -1,
      list: []
    }
  },
  created () {
    this.fetchContact()
  },
  // 利用导航守卫判断这个联系人列表是从哪个页面进去的,如果是提交订单页,点击就可以切换联系人,如果不是,就不做改变
  beforeRouteEnter (to, from, next) {
    localStorage.setItem('from', from.path)
    next()
    // console.log(from)
  },
  methods: {
    // 联系人切换
    selectContact (contact, index) {
      // console.log(contact, index)
      const from = localStorage.getItem('from')
      if (from === '/comfirmOrder') {
        // 说明我是从确认订单页过来的
        this.$router.push({
          path: from,
          query: {
            id: contact.id
          }
        })
      }
    },
    // 新增地址
    onAdd () {
      this.$router.push('/contactAdd')
    },
    onEdit (contact) {
      // 参数1是我将要编辑的联系人
      this.$router.push({
        path: '/contactEdit',
        query: {
          id: contact.id
        }
      })
    },
    fetchContact () {
      fetchContact({
        token: getToken()
      }).then(res => {
        console.log(res)
        if (res.data.code === 0) {
          const contacts = res.data.data.result
          const contactArr = []
          contacts.forEach(contact => {
            const obj = {}
            for (const key in contact) {
              switch (key) {
                case 'id' :
                  obj.id = contact[key]
                  break
                case 'linkMan' :
                  obj.name = contact[key]
                  break
                case 'mobile' :
                  obj.tel = contact[key]
                  break
                case 'address' :
                  obj.address = contact[key]
                  break
                case 'isDefault' :
                  obj.isDefault = contact[key]
                  break
                default:
                  break
              }
            }
            contactArr.push(obj)
          })
          this.list = contactArr
          const contact = this.list.find(contact => contact.isDefault).id
          if (contact) {
            this.chosenAddressId = contact.id
          } else {
            this.chosenAddressId = this.list[0].id
          }
        }
      })
    }
  },
  components: {
    CommonHead
  }

}
</script>

<style lang="scss" scoped>
.wrap{
  padding-top: 46px;
}
</style>
